package LeetCode;

import java.util.*;

public class Code39_combinationSum {

    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        dfs(candidates, new ArrayDeque<>(), 0, target);
        return res;
    }

    private void dfs(int[] arr, Deque<Integer> path, int index,int residue) {
        if (residue == 0){
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = index; i < arr.length; i++) {
            if (residue - arr[index] >= 0){
                path.addLast(arr[index]);
                dfs(arr, path, index, residue - arr[index]);
                path.removeLast();
            }
        }
    }

    public static void main(String[] args) {
        Code39_combinationSum code39_combinationSum = new Code39_combinationSum();
        List<List<Integer>> res = code39_combinationSum.combinationSum(
                new int[]{2,3,6,7}, 7);
        for (int i = 0; i < res.size(); i++) {
            Iterator it = res.iterator();
            while (it.hasNext()){
                List<Integer> l1 = (List<Integer>) it.next();
                for (int j = 0; j < l1.size(); j++) {
                    System.out.print(l1.get(j) + " ");
                }
                System.out.println();
            }
        }
    }
}
